package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.CardInfo;
import com.haotunet.app.goldtreasure.model.CardModel;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class UserNextBuyActivity extends BaseActivity implements OnClickListener {
	private TitleView mTitleView;
	private TextView mSavingBankName, mSavingTailNum, mPayType, mTotalPrice;
	private ImageView ivSaving;
	private EditText mPhoneTxt, mVericodeTxt;
	private Button btnPay;
	private TextView mVericodeBtn;
	private int curTime;
	private Timer timer;
	private OrderInfo orderInfo;
	private List<CardInfo> cardList;
	private String orderPrice;
	private final int GET_MY_BANKCARD_LIST_SUCCESS = 1;
	private Handler handle = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case GET_MY_BANKCARD_LIST_SUCCESS:
				CardModel cardModel = (CardModel) msg.obj;
				cardList = cardModel.getBankCards();
				CardInfo cardInfo = cardList.get(0);
				mSavingBankName.setText(cardInfo.getBankName());
				mSavingTailNum.setText("尾号" + cardInfo.getBankCardlast4());
				ivSaving.setSelected(true);
				mPhoneTxt.setText(cardInfo.getPhone());
				break;

			default:
				break;
			}
		}

	};
	private Handler doActionHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				if (curTime == 0) {
					timer.cancel();
					mVericodeBtn.setText(R.string.get_vericode);
					mVericodeBtn.setTextColor(UserNextBuyActivity.this.getResources().getColor(R.color.color_red));
					mVericodeBtn.setEnabled(true);
				} else {
					mVericodeBtn.setText(curTime + getString(R.string.repeat_after_sixty_seconds));
					mVericodeBtn.setTextColor(UserNextBuyActivity.this.getResources().getColor(R.color.color_red));
				}
				break;

			default:
				break;
			}
		};
	};
	private String type;
	private DBOpenHelper helper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_next_buy);
		helper = new DBOpenHelper(this);
		initView();
		getCradInfo();
	}

	private void initView() {
		Intent intent = this.getIntent();
		type = intent.getStringExtra("type");
		orderInfo = (OrderInfo) intent.getSerializableExtra("orderInfo");
		mTitleView = (TitleView) findViewById(R.id.title_view);
		mTitleView.getTitletextView().setVisibility(View.VISIBLE);
		mTitleView.getTitletextView().setText("确认支付");
		mTitleView.getRightText().setVisibility(View.VISIBLE);
		mTitleView.getRightText().setText("限额说明");
		mTitleView.getRightText().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ActivityUtils.gotoDynamicDetail(UserNextBuyActivity.this, UrlUtil.SUPPORT_BANK, 2);
			}
		});
		mTitleView.getBackView().setVisibility(View.VISIBLE);
		mTitleView.getBackView().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setResult(RESULT_OK);
				finish();
			}
		});
		mPayType = (TextView) findViewById(R.id.pay_type);
		mTotalPrice = (TextView) findViewById(R.id.total_price);
		if (type.equals("1")) {
			orderPrice = orderInfo.getCurrentOrderPrice();
			mTotalPrice.setText(orderInfo.getCurrentOrderPrice() + "元");
		} else if (type.equals("2")) {
			mPayType.setText("钱包充值");
			orderPrice = orderInfo.getPayment();
			mTotalPrice.setText(orderInfo.getPayment() + "元");
		} else if (type.equals("3")) {
			mPayType.setText("支付手续费");
			orderPrice = orderInfo.getFee();
			mTotalPrice.setText(orderInfo.getFee() + "元");
		} else if (type.equals("4")) {
			mPayType.setText("手续费");
			orderPrice = orderInfo.getPayment();
			mTotalPrice.setText(orderInfo.getPayment() + "元");
		}
		mSavingBankName = (TextView) findViewById(R.id.saving_card_bank_name);
		mSavingTailNum = (TextView) findViewById(R.id.saving_card_tail_num);
		ivSaving = (ImageView) findViewById(R.id.saving_card_select_btn);

		mPhoneTxt = (EditText) findViewById(R.id.et_phone);
		mVericodeTxt = (EditText) findViewById(R.id.et_vericode);
		mVericodeBtn = (TextView) findViewById(R.id.btn_get_nextbuy_vericode);
		btnPay = (Button) findViewById(R.id.btn_pay);
		mVericodeBtn.setOnClickListener(this);
		btnPay.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {

		case R.id.saving_card_select_btn:
			if (cardList.size() == 2) {
				ivSaving.setSelected(true);
			}
			break;

		case R.id.btn_get_nextbuy_vericode:
			String phone = mPhoneTxt.getText().toString().trim();
			if (TextUtils.isEmpty(phone)) {
				UIHelper.showToast(UserNextBuyActivity.this, "请输入手机号!");
				return;
			}

			getPayCode(orderInfo.getOrderNo(), cardList.get(0).getRealName(), cardList.get(0).getCardNo(),
					cardList.get(0).getIdCard(), phone, orderPrice, helper.getUserId());

			break;
		case R.id.btn_pay:
			String vericode = mVericodeTxt.getText().toString().trim();
			if (TextUtils.isEmpty(vericode)) {
				UIHelper.showToast(UserNextBuyActivity.this, "请输入验证码!");
				return;
			}

			submitNextBuyInfo(vericode);

			break;
		default:
			break;
		}
	}

	private void getCradInfo() {
		ActionUtil actionUtil = new ActionUtil(UserNextBuyActivity.this);
		actionUtil.getMyBankCardList();
		actionUtil.setOnPassBackListener(new OnPassBackListener() {

			@Override
			public void passBack(BaseModel model) {
				CardModel cardModel = (CardModel) model;
				if (cardModel == null) {
					UIHelper.showToast(UserNextBuyActivity.this, getString(R.string.rank_fail));
					return;
				}
				if (cardModel.getErrorMsg() != null) {
					UIHelper.showToast(UserNextBuyActivity.this, cardModel.getErrorMsg());
				} else {
					Message msg = new Message();
					msg.what = GET_MY_BANKCARD_LIST_SUCCESS;
					msg.obj = cardModel;
					handle.sendMessage(msg);
				}
			}
		});

	}

	private void submitNextBuyInfo(String code) {
		ActionUtil actionUtil = new ActionUtil(UserNextBuyActivity.this);
		actionUtil.submitPayInfo("",orderInfo.getOrderNo(), code,"","");
		actionUtil.setOnPassBackListener(new OnPassBackListener() {

			@Override
			public void passBack(BaseModel model) {

				if (model == null) {
					UIHelper.showToast(UserNextBuyActivity.this, getString(R.string.rank_fail));
					return;
				}
				if (model.getErrorMsg() != null) {
					if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
						ActivityUtils.forceQuit(UserNextBuyActivity.this,getString(R.string.crowding_in_tips_txt));
					} else {
						UIHelper.showToast(UserNextBuyActivity.this, model.getErrorMsg());
					}
				} else {
					if ("true".equals(model.getStatus())) {
						String type = null;
						if ("HQ".equals(orderInfo.getOrderNo().substring(0, 2))) {
							type = "buyCurrentSuccess";
						} else {
							type = "buyRegularSuccess";
						}
						ActivityUtils.gotoTransRecord(UserNextBuyActivity.this, type);
					} else {
						UIHelper.showToast(UserNextBuyActivity.this, model.getInfo());
					}
				}
			}
		});
	}

	private void getPayCode(String orderNo, String realName, String cardNo, String idNo, String mobile,
			String orderAmount, String userID) {
		ActionUtil actionUtil = new ActionUtil(UserNextBuyActivity.this);
		actionUtil.getPayCode(orderNo, realName, cardNo, idNo, mobile, orderAmount,"","");
		actionUtil.setOnPassBackListener(new OnPassBackListener() {

			@Override
			public void passBack(BaseModel model) {
				if (model == null) {
					UIHelper.showToast(UserNextBuyActivity.this, getString(R.string.rank_fail));
					return;
				}
				if (model.getErrorMsg() != null) {
					if (model.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
						ActivityUtils.forceQuit(UserNextBuyActivity.this,getString(R.string.crowding_in_tips_txt));
					} else {
						UIHelper.showToast(UserNextBuyActivity.this, model.getErrorMsg());
					}
				} else {
					if ("true".equals(model.getStatus())) {
						UIHelper.showToast(UserNextBuyActivity.this, getString(R.string.vericode_send_success));
						setTimerTask();
						mVericodeBtn.setEnabled(false);
					} else {
						UIHelper.showToast(UserNextBuyActivity.this, model.getInfo());
					}
				}
			}
		});
	}

	private void setTimerTask() {
		curTime = 60;
		timer = new Timer();
		timer.schedule(new TimerTask() {

			@Override
			public void run() {

				Message msg = new Message();
				msg.what = 1;
				doActionHandler.sendMessage(msg);
				curTime--;
			}
		}, 0, 1000);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_OK);
		}
		return super.onKeyUp(keyCode, event);
	}
}
